<?php

namespace App\Http\Controllers\Home\User;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Home\Part as PartModel;
use App\Models\Home\Users as UsersModel;
use Illuminate\Support\Facades\Hash;
use Part;
use Frame;
use Tools;
use Auth;

class PartController extends Controller
{
    protected $passField = [
        'chinese_name','english_name','abbreviation_name','url','contacts','duties','sex','country_code','phone','company_phone','email','related_url','company_address','area','situation','brief','care','uid','assign','assign_time','share','status','create_uid','create_username','create_user_password','create_status'
    ];
    protected $job;

    public function __construct()
    {
        $this->job = get_config_cache('job');
    }

    public function part_list(Request $request)
    {
        $in = [];

        if (!Auth::user()->hasRole('admin')){

            $user = Auth::user()->load('frame');

            $member = Frame::getMember($user->frame->id);

            $member[] = Auth::id();

            $in = ['assign',$member];
        }

        $page = $request->input('page');

        $page_info = Tools::page_helper($page,config('base.home_limit.base_limit.render_limit'),config('base.home_limit.base_limit.limit'));

        $list = Part::getList($page_info['skip'],$page_info['limit'],[],$in);

        $count = Part::getCount([],$in);

        $num = intval(ceil($count/config('base.home_limit.base_limit.limit')));

        $job_day = $this->job;

        return view('Home.User.Channel.Part.part_list',compact('list','page','num','job_day'));
    }

    public function add(Request $request){
        if($request->isMethod('post')){
            //验证
            $rules = [
                'chinese_name' => 'required|string',
                'english_name' => 'nullable|string',
                'abbreviation_name' => 'required|string|unique:part',
                'replace_name' => 'nullable|string',
                'url' => 'nullable|string',
                'contacts' => 'required|string',
                'duties' => 'nullable|string',
                'sex' => 'integer',
                'country_code' => [function ($attribute, $value, $fail) {
                    if (!intval($value)) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'phone' => ['required','integer',function ($attribute, $value, $fail) {
                    $country_code = trim(request()->input('country_code'));
                    if ($country_code){
                        $value = trim($value);
                        $client = PartModel::where('country_code',$country_code)->where('phone',$value)->where('status',1)->first();
                        if ($client){
                            $fail(':attribute 已存在。');
                        }
                    }
                }],
                'company_phone' => 'required|string',
                'email' => 'required|string',
                'related_url' => 'nullable|string',
                'company_address' => 'nullable|string',
                'area' => 'required|string',
                'brief' => 'required|string',
                'care' => 'nullable|string',
                'create_username' => 'required|string|unique:users,username',
                'create_user_password' => 'required|string|min:8',
                'create_status' => 'required|integer',
                'situation' => 'nullable|integer',
                'shareTo' => 'required|integer',
            ];

            $customAttributes = [
                'chinese_name' => '公司中文名称',
                'english_name' => '公司英文名称',
                'abbreviation_name' => '公司简称',
                'replace_name' => '替代名称',
                'url' => '公司网站地址',
                'contacts' => '公司联系人',
                'duties' => '职务',
                'sex' => '性别',
                'country_code' => '国家区号',
                'phone' => '手机',
                'company_phone' => '公司电话',
                'email' => 'Email',
                'related_url' => '其它相关网址',
                'company_address' => '公司地址',
                'area' => '所在地区',
                'brief' => '公司简介及福利',
                'care' => '客户关心重点',
                'create_username' => '兼职者账户名',
                'create_user_password' => '兼职者账户密码',
                'create_status' => '兼职者账户状态',
                'situation' => '沟通情况',
                'shareTo' => '任务归属',
            ];

            if (intval(request()->post('situation')) != 3){
                unset($rules['create_username'],$rules['create_user_password'],$rules['create_status']);
            }

            $this->validate(request(),$rules,[],$customAttributes);

            //数据库操作
            $data = [];
            foreach ($request->all() as $key => $val){
                if (!is_numeric($val)){	$val = clean($val);}
                if(in_array($key,$this->passField)){
                    $data[$key] = $val;
                }
            }

            if ($data['situation'] == 3){
                if (isset($data['create_username']) && isset($data['create_user_password'])){
                    $create_user_data['username'] = $data['create_username'];
                    $create_user_data['password'] = Hash::make($data['create_user_password']);
                    $create_user_data['status'] = $data['create_status'];
                    $create_user_data['type'] = config('base.user_type.part');
                    if ($user = UsersModel::create($create_user_data)){
                        $user->assignRole('external');
                        $data['create_uid'] = $user->id;
                    }
                }
            }

            switch (intval(request()->post('shareTo'))){
                case 1:
                    $data['assign'] = Auth::id();
                    $data['assign_time'] = strtotime('+ '.$this->job.' day',time());
                    $data['share'] = 0;
                    break;
                case 2:
                    $data['assign'] = '';
                    $data['assign_time'] = '';
                    $data['share'] = 1;
                    break;
                case 3:
                    if ($assign = intval(request()->post('assign'))){
                        $data['assign'] = $assign;
                        $data['assign_time'] = strtotime('+ '.$this->job.' day',time());
                        $data['share'] = 0;
                    }else{
                        $data['assign'] = '';
                        $data['assign_time'] = '';
                        $data['share'] = 1;
                    }
                    break;
                default:
                    $data['assign'] = '';
                    $data['assign_time'] = '';
                    $data['share'] = 1;
            }

            $data['uid'] = Auth::id();
            $res = PartModel::create($data);

            return ['code'=>1];
            //返回结果
        }
        $frame = Frame::GetFrame(config('base.branch.lg.id'),config('base.level.admin'));

        $job_day = $this->job;

        return view('Home.User.Channel.Part.part_add',compact('frame','job_day'));
    }

    public function edit(PartModel $obj){
        $obj->load(['user','create_user']);

        if(request() ->isMethod('post')){
            //验证
            $rules = [
                'chinese_name' => 'required|string',
                'english_name' => 'nullable|string',
                'abbreviation_name' => ['required','string',function ($attribute, $value, $fail) use($obj){
                    if ($obj->abbreviation_name != trim($value)) {
                        $user = PartModel::where('abbreviation_name', trim($value))->where('status', 1)->first();
                        if ($user) {
                            $fail(':attribute 已存在。');
                        }
                    }
                }],
                'replace_name' => 'nullable|string',
                'url' => 'nullable|string',
                'contacts' => 'nullable|string',
                'duties' => 'nullable|string',
                'sex' => 'integer',
                'country_code' => [function ($attribute, $value, $fail) {
                    if (!intval($value)) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'phone' => ['required','integer',function ($attribute, $value, $fail) use($obj){
                    $country_code = trim(request()->input('country_code'));
                    if ($country_code){
                        $value = trim($value);
                        if (trim($obj->country_code.$obj->phone) != $country_code.$value){
                            $client = PartModel::where('country_code',$country_code)->where('phone',$value)->where('status',1)->first();
                            if ($client){
                                $fail(':attribute 已存在。');
                            }
                        }
                    }
                }],
                'company_phone' => 'required|string',
                'email' => 'required|string',
                'related_url' => 'nullable|string',
                'company_address' => 'nullable|string',
                'area' => 'required|string',
                'brief' => 'required|string',
                'care' => 'nullable|string',
                'create_username' => ['required','string',function ($attribute, $value, $fail) use($obj){
                    if ($obj->create_username != trim($value)) {
                        $user = UsersModel::where('username', trim($value))->where('status', 1)->first();
                        if ($user) {
                            $fail(':attribute 已存在。');
                        }
                    }
                }],
                'create_user_password' => 'required|string|min:8',
                'create_status' => 'required|integer',
                'situation' => 'required|integer',
                'shareTo' => 'required|integer',
            ];

            $customAttributes = [
                'chinese_name' => '公司中文名称',
                'english_name' => '公司英文名称',
                'abbreviation_name' => '公司简称',
                'replace_name' => '替代名称',
                'url' => '公司网站地址',
                'contacts' => '公司联系人',
                'duties' => '职务',
                'sex' => '性别',
                'country_code' => '国家区号',
                'phone' => '手机',
                'company_phone' => '公司电话',
                'email' => 'Email',
                'related_url' => '其它相关网址',
                'company_address' => '公司地址',
                'area' => '所在地区',
                'brief' => '公司简介及福利',
                'care' => '客户关心重点',
                'create_username' => '兼职者账户名',
                'create_user_password' => '兼职者账户密码',
                'create_status' => '兼职者账户状态',
                'situation' => '沟通情况',
                'shareTo' => '任务归属',
            ];

            if (intval(request()->post('situation')) != 3){
                unset($rules['create_username'],$rules['create_user_password'],$rules['create_status']);
            }

            if ($obj->assign == Auth::id() && $obj->uid != Auth::id() && !Auth::user()->hasRole('admin')){
                foreach ($rules as $k => $v){
                    if ($k != 'shareTo'){
                        unset($rules[$k]);
                    }
                }
            }

            $this->validate(request(),$rules ,[],$customAttributes);

            //数据库操作
            foreach (request()->all() as $key => $val){
                if (!is_numeric($val)){	$val = clean($val);}
                if(in_array($key,$this->passField)){
                    $obj->$key = $val;
                }
            }

            if ($obj->situation == 3){
                if (request()->post('create_username') && request()->post('create_user_password')){
                    $obj->load(['create_user']);
                    $obj->create_username = trim(request()->post('create_username'));
                    $obj->create_user_password = request()->post('create_user_password');
                    $obj->create_status = request()->post('create_status');
                    $create_user['username'] = $obj->create_username;
                    $create_user['password'] = Hash::make($obj->create_user_password);
                    $create_user['status'] = $obj->create_status;
                    $create_user['type'] = config('base.user_type.part');
                    $create_user['frame_id'] = trim(request()->post('assign'));

                    if ($obj->create_user){
                        $obj->create_user->username = $create_user['username'];
                        $obj->create_user->password = $create_user['password'];
                        $obj->create_user->status = $create_user['status'];
                        $obj->create_user->type = $create_user['type'];
                        $obj->create_user->frame_id = request()->post('assign');
                        $obj->create_user->save();
                    }else{
                        $user = UsersModel::create($create_user);
                        $user->assignRole('external');
                        $obj->create_uid = $user->id;
                    }
                }
            }

            switch (intval(request()->post('shareTo'))){
                case 1:
                    $obj->assign = Auth::id();
                    $obj->assign_time = strtotime('+ '.$this->job.' day',time());
                    $obj->share = 0;
                    break;
                case 2:
                    $obj->assign = '';
                    $obj->assign_time = '';
                    $obj->share = 1;
                    break;
                case 3:
                    if ($assign = intval(request()->post('assign'))){
                        $obj->assign = $assign;
                        $obj->assign_time = strtotime('+ '.$this->job.' day',time());
                        $obj->share = 0;
                    }else{
                        $obj->assign = '';
                        $obj->assign_time = '';
                        $obj->share = 1;
                    }
                    break;
                default:
                    $obj->assign = '';
                    $obj->assign_time = '';
                    $obj->share = 1;
            }

            $res = $obj->save();
            //返回结果
            return ['code'=>1];
        }

        $obj = Part::SetAssign($obj);

        if ($obj->assign){
            if ($obj->assign == Auth::id()){
                $obj->shareTo = 1;
            }else{
                $obj->shareTo = 3;
            }
        }else{
            $obj->shareTo = 2;
        }

        $frame = Frame::GetFrame(config('base.branch.lg.id'),config('base.level.admin'));

        $job_day = $this->job;

        return view('Home.User.Channel.Part.part_edit',compact('obj','frame','job_day'));
    }

    public function del(PartModel $obj)
    {
        if(Auth::user()->hasAnyRole(['admin']) || Auth::id()==$obj->uid){

            $obj->status = 0;

            $res = $obj->save();

            if ($res){

                $rerurn = ['code'=>1,'msg'=>'OK'];

            }else{

                $rerurn = ['code'=>0,'msg'=>'服务器错误'];
            }
        }else{

            $rerurn = ['code'=>0,'msg'=>'没有权限'];
        }

        return $rerurn;
    }

}